package com.hpin.mlxteacher.message;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.hpin.mlxteacher.R;
import com.hpin.mlxteacher.adapter.ChooseAdapter;
import com.hpin.mlxteacher.adapter.SchoolClassAdapter;
import com.hpin.mlxteacher.base.BaseActivity;
import com.hpin.mlxteacher.bean.SchoolClassReq;
import com.hpin.mlxteacher.bean.SchoolResultBean;
import com.hpin.mlxteacher.utils.CommonUtils;
import com.hpin.mlxteacher.utils.Constant;
import com.hpin.mlxteacher.utils.DensityUtil;
import com.hpin.mlxteacher.utils.HttpUtil;
import com.hpin.mlxteacher.utils.LogUtil;
import com.hpin.mlxteacher.widget.GridViewForScrollView;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

//import com.umeng.analytics.MobclickAgent;

/**
 * 选择收件人页面
 * Created by Aaron on 2015/7/21.
 */
public class ReceiverActivity extends BaseActivity {

    private ChooseAdapter chooseAdapter;
    private TextView tv_school;
    private TextView tv_child;
    private SchoolClassReq classReq;
    private List<SchoolResultBean.Data> datas;
    private SchoolClassAdapter schoolClassAdapter;
//    private String childIds;
    /**
     * 收件人code
     */
    private static final int RECEIVER_CODE = 1008;
    private GridViewForScrollView gv_receiver;
    private int style = 0;//选择的是学校  还是  孩子

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_choose_receiver);

        initWidget();

        //如果没有选择班级 则获取班级信息
        if (CommonUtils.isNull(sp.getString(Constant.classId, ""))) {
            onChildSelect();
            myClasses(tv_child);
        } else {
            //选择了班级
            getChildList(Constant.RECEIVEPEOPLELIST);
        }

        //获取 学校分类的 孩子列表
//        getChildList(Constant.RECEIVEPEOPLELIST);
//        childIds = sp.getString(Constant.childIds,"");
    }

    private TextView tv_left;

    private void initWidget() {

        tv_left = (TextView) findViewById(R.id.tv_left);

        tv_school = (TextView) findViewById(R.id.tv_school);
        tv_child = (TextView) findViewById(R.id.tv_child);

        TextView tv_right = (TextView) findViewById(R.id.tv_right);

        tv_left.setText(getResources().getString(R.string.select_all));
        tv_right.setText(getResources().getString(R.string.done));

        onSchoolSelect();

        gv_receiver = (GridViewForScrollView) findViewById(R.id.gv_peoplel);

        gv_receiver.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //反选 收件人
//                ((People) chooseAdapter.getItem(position)).isSelect =  (((People) chooseAdapter.getItem(position)).isSelect) == 0 ? 1 : 0;
                ((SchoolResultBean.Data) chooseAdapter.getItem(position)).isSelect = !((SchoolResultBean.Data) chooseAdapter.getItem(position)).isSelect;

                chooseAdapter.notifyDataSetChanged();
            }
        });

        tv_left.setOnClickListener(this);
        tv_right.setOnClickListener(this);

        tv_school.setOnClickListener(this);
        tv_child.setOnClickListener(this);

    }

    /**
     * 获取 学校分类的 孩子列表
     *
     * @param childType 请求的是学校 还是班级 的url
     */
    private void getChildList(String childType) {


        JSONObject j = new JSONObject();
        j.put("token", sp.getString(Constant.token, ""));

        if (childType.equals(Constant.GETCHILDERN))
            j.put("classId", sp.getString(Constant.classId, ""));

        HttpUtil.setPostRequest("正在获取孩子信息...", this, Constant.WEB_ROOT + childType, j.toJSONString(),
                getClass().getName(), new HttpUtil.SuccessListener() {
                    @Override
                    public void setOnSuccessListener(String str) {

                        try {

                            SchoolResultBean schoolResultBean = JSONObject.parseObject(str, SchoolResultBean.class);

                            if (schoolResultBean.code == Constant.SUCCESS) {
                                datas = schoolResultBean.data;

                                chooseAdapter = new ChooseAdapter(ReceiverActivity.this, datas);
                                gv_receiver.setAdapter(chooseAdapter);

                            } else {
                                showToast(Constant.showErrorMsg(schoolResultBean.code, ReceiverActivity.this));
                            }

                        } catch (Exception e) {

                            showToast(Constant.NODATA);
                            e.printStackTrace();
                            LogUtil.e("TAG", "获取学校孩子联系人数据解析错误");

                        }
                    }
                }, null);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        mApplication.cancelPendingRequests(getClass().getName());

    }

    @Override
    public void widgetClick(View v) {
        switch (v.getId()) {

            case R.id.tv_left:
                //全选
                if (datas == null) {
                    return;
                }

                String Select = tv_left.getText().toString().trim();
                if ("全选".equals(Select)) {
                    tv_left.setText("取消");
                    for (SchoolResultBean.Data p : datas) {

                        p.isSelect = true;
                    }

                } else if ("取消".equals(Select)) {
                    tv_left.setText("全选");

                    for (SchoolResultBean.Data p : datas) {
                        p.isSelect = false;
                    }
                }

                chooseAdapter.notifyDataSetChanged();

                break;
            case R.id.tv_right:
                //完成
                if (datas == null) {
                    finish();
                    return;
                }

                List<SchoolResultBean.Data> chooseedPeoples = new ArrayList<SchoolResultBean.Data>();

                for (SchoolResultBean.Data p : datas) {

                    if (p.isSelect) {
                        chooseedPeoples.add(p);
                    }
                }
                Intent data = new Intent();
                data.putExtra("chooseedPeoples", (Serializable) chooseedPeoples);
//                if (style == 0) {
//                    //说明选的是学校
                data.putExtra("style", style);//0 是学校 1是孩子
//                }else {//选择的是孩子
//
//                }
                setResult(RECEIVER_CODE, data);
                finish();


                break;
            case R.id.tv_school: //学校

                style = 0;

                onSchoolSelect();
                tv_left.setText("全选");

                if (datas == null || datas.size() < 1) {
                    return;
                }

                for (SchoolResultBean.Data p : datas) {

                    p.isSelect = true;
                }
                if (datas != null) {
                    datas.clear();
                    chooseAdapter.setDatas(datas);
                    chooseAdapter.notifyDataSetChanged();
                }
                if (datas != null) {
                    datas.clear();
                    chooseAdapter.setDatas(datas);
                    chooseAdapter.notifyDataSetChanged();
                }

                //获取 学校分类的 孩子列表
                getChildList(Constant.RECEIVEPEOPLELIST);

                break;
            case R.id.tv_child: //孩子

                style = 1;

                onChildSelect();
                tv_left.setText("全选");

                if (datas != null && datas.size() > 0) {
                    for (SchoolResultBean.Data p : datas) {

                        p.isSelect = true;
                    }
                    if (datas != null) {
                        datas.clear();
                        chooseAdapter.setDatas(datas);
                        chooseAdapter.notifyDataSetChanged();
                    }
                }


                if (classReq != null)
                    showPup(classReq, v);//已经加载过班级信息 直接弹出提示
                else
                    myClasses(v);//未加载过班级信息, 先获取班级信息

                break;

        }
    }

    /**
     * 弹出选择popu的窗口
     *
     * @param classReq
     * @param v
     */
    private void showPup(final SchoolClassReq classReq, View v) {

        View popuView = View.inflate(this, R.layout.layout_choose_class, null);

        final PopupWindow classDialog = new PopupWindow(popuView,
                DensityUtil.dip2px(this, 75), ViewGroup.LayoutParams.WRAP_CONTENT);
        classDialog.setOutsideTouchable(true);
        classDialog.setFocusable(true);
        classDialog.setBackgroundDrawable(new BitmapDrawable());
        //x y   DensityUtil.dip2px(getActivity(), 5)
//        classDialog.showAsDropDown(v, 0, DensityUtil.dip2px(getActivity(), 5)); //0 0  x y 轴的偏移量
        classDialog.showAsDropDown(v, 0, 0); //0 0  x y 轴的偏移量
//        //屏幕变暗
//        changeScreen(0.5f);

        ListView lv_class = (ListView) popuView.findViewById(R.id.lv_class);

//        temList = classReq.data;
        schoolClassAdapter = new SchoolClassAdapter(this, classReq.data);

        lv_class.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                //选择班级
                if (classReq != null && classReq.data != null && classReq.data.size() > 0) {
//                    currentClassId = classReq.data.get(i).id;
                    //保存班级名称和id
                    SharedPreferences.Editor edit = sp.edit();
                    edit.putString(Constant.classId, classReq.data.get(i).id);
                    edit.putString(Constant.className, classReq.data.get(i).nickName);
                    edit.apply();

                    getChildList(Constant.GETCHILDERN);

                }

                if (classDialog != null && classDialog.isShowing())
                    classDialog.dismiss();

            }
        });
        lv_class.setAdapter(schoolClassAdapter);

    }

    /**
     * 选中了学校 改变字体和背景颜色
     */
    private void onSchoolSelect() {
        tv_school.setTextColor(getResources().getColor(R.color.white));
        tv_school.setBackgroundDrawable(getResources().getDrawable(R.drawable.ic_bg_whitehei));
        tv_child.setTextColor(getResources().getColor(R.color.font_black));
        tv_child.setBackgroundDrawable(null);
    }

    /**
     * 选中了孩子 改变字体和背景颜色
     */
    private void onChildSelect() {
        tv_child.setTextColor(getResources().getColor(R.color.white));
        tv_child.setBackgroundDrawable(getResources().getDrawable(R.drawable.ic_bg_white_righthei));
        tv_school.setTextColor(getResources().getColor(R.color.font_black));
        tv_school.setBackgroundDrawable(null);
    }

    /**
     * 获取我的班级
     */
    private void myClasses(final View v) {

        JSONObject j = new JSONObject();
        j.put("token", sp.getString(Constant.token, ""));

        HttpUtil.setPostRequest("获取班级中...", this, Constant.WEB_ROOT + Constant.MYCLASSES,
                j.toJSONString(), getClass().getName(), new HttpUtil.SuccessListener() {
                    @Override
                    public void setOnSuccessListener(String str) {

                        try {

                            classReq = JSONObject.parseObject(str, SchoolClassReq.class);

                            if (classReq.code == Constant.SUCCESS) {

                                if (classReq != null && classReq.data != null && classReq.data.size() > 0) {

                                    showPup(classReq, v);
                                }

                            } else
                                showToast(Constant.showErrorMsg(classReq.code, ReceiverActivity.this));

                        } catch (Exception e) {
                            e.printStackTrace();
                            showToast(Constant.NODATA);
                        }

                    }
                }, null);

    }

//
//    public void onResume() {
//        super.onResume();
//        MobclickAgent.onResume(this);       //统计时长
//    }
//
//    public void onPause() {
//        super.onPause();
//        MobclickAgent.onPause(this);
//    }
}
